// 引入工具
import { checkUserData } from '~/assets/js/util'

const userToken = () => {
  return checkUserData() ? checkUserData().userToken : ''
}

const httpGet = async ({
  context = {},
  url = '',
  params = {},
  token = userToken(),
  errorCallback = () => {}
} = {}) => {
  try {
    const { status, msg, data } = await context.$axios.$get(`/api/${url}`, {
      params,
      headers: {
        YDSY_HEADER_TOKEN: token
      }
    })
    return dealResponse({ status, msg, data, errorCallback, context })
  } catch (e) {
    console.log(e)
  }
}

const httpPost = async ({
  context = {},
  url = '',
  params = {},
  token = userToken(),
  errorCallback = () => {}
} = {}) => {
  try {
    const { status, msg, data } = await context.$axios.$post(`/api/${url}`, params, {
      headers: {
        YDSY_HEADER_TOKEN: token
      }
    })
    return dealResponse({ status, msg, data, errorCallback, context })
  } catch (e) {
    console.log(e)
  }
}

const httpPut = async ({
  context = {},
  url = '',
  params = {},
  token = userToken(),
  errorCallback = () => {}
} = {}) => {
  try {
    const { status, msg, data } = await context.$axios.$put(`/api/${url}`, params, {
      headers: {
        YDSY_HEADER_TOKEN: token,
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
    return dealResponse({ status, msg, data, errorCallback, context })
  } catch (e) {
    console.log(e)
  }
}

const httpDelete = async ({
  context = {},
  url = '',
  params = {},
  token = userToken(),
  errorCallback = () => {}
} = {}) => {
  try {
    const { status, msg, data } = await context.$axios.$delete(`/api/${url}`, {
      data: params,
      headers: {
        YDSY_HEADER_TOKEN: token
      }
    })
    return dealResponse({ status, msg, data, errorCallback, context })
  } catch (e) {
    console.log(e)
  }
}

// 处理响应
const dealResponse = ({
  status = null,
  data = {},
  msg = '',
  errorCallback,
  context
} = {}) => {
  if (status === 200) {
    return data || msg || true
  } else {
    context.$alert(msg || '请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      lockScroll: false,
      callback: errorCallback
    })
    return false
  }
}

const httpRequest = ({
  context = {},
  method = 'get',
  url = '',
  params = {},
  token = userToken(),
  errorCallback = () => {}
} = {}) => {
  switch (method) {
    case 'get':
      return httpGet({ context, url, params, token, errorCallback })
    case 'post':
      return httpPost({ context, url, params, token, errorCallback })
    case 'put':
      return httpPut({ context, url, params, token, errorCallback })
    case 'delete':
      return httpDelete({ context, url, params, token, errorCallback })
  }
}

export default ({ app }, inject) => {
  inject('request', httpRequest)
}
